package com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.css.fxfzxczh.constants.YNEnum;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.entity.SamPoiData;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.queryParams.SamPoiDataQuaParams;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.repository.SamPoiDataRepository;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.service.SamPoiDataService;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.verify.SamPoiExcelVerifyHandler;
import com.css.fxfzxczh.modules.fieldWorkManage.lnvestigationTaskMange.entity.InvestigationTask;
import com.css.fxfzxczh.modules.fieldWorkManage.lnvestigationTaskMange.repository.InvTaskManageRepository;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.entity.SurTaskManage;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.repository.SurTaskManageRepository;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.entity.ReportPublicField;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.repository.ReportPublicFieldRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.EarEveManage;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.service.EarEveManageService;
import com.css.fxfzxczh.util.CreateGson;
import com.css.fxfzxczh.util.EasyPoiExcelUtil;
import com.css.fxfzxczh.util.PlatformObjectUtils;
import com.css.fxfzxczh.util.UUIDGenerator;
import com.css.fxfzxczh.web.PlatformSessionContext;
import com.css.fxfzxczh.zcpt.sys.entity.SUser;
import com.css.fxfzxczh.zcpt.sys.service.SUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SamPoiDataServiceImpl implements SamPoiDataService {

    @Resource
    SamPoiDataRepository samPoiDataRepository;

    @Resource
    SUserService sUserService;

    @Autowired
    EarEveManageService earEveManageService;

    @Autowired
    SamPoiExcelVerifyHandler samPoiExcelVerifyHandler;

    @Autowired
    ReportPublicFieldRepository reportPublicFieldRepository;

    @Resource
    SurTaskManageRepository surTaskManageRepository;

    @Resource
    InvTaskManageRepository invTaskManageRepository;

    @Override
    public Map<String, Object> getPage(SamPoiDataQuaParams queParams, int curPage, int pageSize) {
        Map<String, Object> page = samPoiDataRepository.getPage(queParams, curPage, pageSize);
        return page;
    }

    @Override
    public void save(SamPoiData samPoiData) {
        String userID = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userID);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        samPoiData.setCreateUserName(sUser.getUserName());
        samPoiData.setId(UUIDGenerator.getUUID());
        samPoiData.setCreateTime(new Date());
        samPoiData.setCreateUser(userID);
        samPoiData.setDelFlag(YNEnum.N.toString());
        samPoiData.setGeom("POINT("+samPoiData.getLongitude()+" "+samPoiData.getLatitude()+")");
        samPoiDataRepository.save(samPoiData);
    }

    @Override
    public void exportExcel(HttpServletResponse response, SamPoiDataQuaParams queryParams) {
        List<SamPoiData> list = samPoiDataRepository.getSamPoiDataList(queryParams);
        if (list.size() <= 0) {
            throw new RuntimeException("数据为空,无法导出！");
        }
        try {
            EasyPoiExcelUtil.exportExcel(list, "抽样点数据信息统计", "抽样点数据信息", SamPoiData.class, "抽样点数据信息", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getSamPoiCode(String eventCode) {
        EarEveManage currentEvent = earEveManageService.getCurrentEvent();
        eventCode=currentEvent.getEventCode();
        StringBuilder samPoiCode = new StringBuilder(eventCode+"CYD");
        DecimalFormat decimalFormat=new DecimalFormat("000");
        String num="";

        String maxNum=samPoiDataRepository.getMaxNum(samPoiCode.toString());
        if(PlatformObjectUtils.isEmpty(maxNum)){
            int i = 1;
            num=decimalFormat.format(i);
        }else{
            String substring = maxNum.substring(maxNum.length()-3);
            num = decimalFormat.format(Integer.parseInt(substring) + 1);
        }
        return samPoiCode.append(num).toString();
    }

    @Override
    public SamPoiData findById(String id) {
        SamPoiData samPoiData=samPoiDataRepository.findById(id);
        return samPoiData;
    }

    @Override
    public List<SamPoiData> getSamPoiList(String xsemId) {
        return samPoiDataRepository.getSamPoiList(xsemId);
    }

    @Override
    public void update(SamPoiData samPoiData) {
        samPoiData.setUpdateTime(new Date());
        samPoiData.setUpdateUser(PlatformSessionContext.getUserID());
        samPoiDataRepository.update(samPoiData);
    }

    @Override
    public void delete(String ids) {
        String[] split = ids.split(",");
        for(String id:split){
            samPoiDataRepository.delete(id);
        }
    }

    @Override
    public List<SamPoiData> getSamPoiListByXstmId(String xstmId) {
        return samPoiDataRepository.getSamPoiListByXstmId(xstmId);
    }

    @Override
    public Map<String, Object> importExcel(MultipartFile file, String xsemId, String xitmId) {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        params.setTitleRows(1);
        params.setImportFields(new String[]{"省","市","区(县)","详细地址","经度","纬度","抽样点名称"});
        params.setNeedVerify(true);
        params.setVerifyHandler(samPoiExcelVerifyHandler);
        boolean res = false;
        Map<String, Object> map = new HashMap<>();
        try {
            String userId = PlatformSessionContext.getUserID();
            String user = sUserService.getSUser(userId);
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            String userName = sUser.getUserName();
            EarEveManage currentEvent = earEveManageService.getCurrentEvent();//获取当前地震事件
            InputStream inputStream = file.getInputStream();
            ExcelImportResult<SamPoiData> result = ExcelImportUtil.importExcelMore(inputStream, SamPoiData.class, params);
            List<SamPoiData> failList = result.getFailList();
            if (PlatformObjectUtils.isNotEmpty(failList)) {
                StringBuilder errorMsg = new StringBuilder("<font size='5px' color='red'>导入失败：</font>");
                for(SamPoiData samPoiData : failList){
                    errorMsg.append("<font size='4px' ><br>").append("第").append(samPoiData.getRowNum() + 1).append("行： ").append(samPoiData.getErrorMsg()).append("</font>");
                }
                map.put("res",res);
                map.put("mess",errorMsg);
                return map;
            }
            List<SamPoiData> resultData = result.getList();//解析excel
            for(SamPoiData samPoiData : resultData){
                InvestigationTask byId = invTaskManageRepository.findById(xitmId);
                String uuid = UUIDGenerator.getUUID();
                samPoiData.setId(uuid);
                samPoiData.setXsemId(xsemId);
                samPoiData.setXitmId(xitmId);
                String samPoiCode = getSamPoiCode(currentEvent.getEventCode());//抽样点编号
                samPoiData.setSamplingPointCode(samPoiCode);
                samPoiData.setDelFlag("0");
                samPoiData.setCreateUserName(userName);
                samPoiData.setCreateUser(userId);
                samPoiData.setCreateTime(new Date());
                //samPoiData.setType();
                String longitude = samPoiData.getLongitude().toString();
                String latitude = samPoiData.getLatitude().toString();
                String geom = "POINT("+longitude+" "+latitude+")";
                samPoiData.setGeom(geom);
                res = samPoiDataRepository.save(samPoiData);

                //保存专门维护省市区县的表
                ReportPublicField reportPublicField = new ReportPublicField();
                reportPublicField.setXlrmId(uuid);
                reportPublicField.setXsemId(xsemId);
                reportPublicField.setProvince(samPoiData.getProvince());
                reportPublicField.setCity(samPoiData.getCity());
                reportPublicField.setCounty(samPoiData.getArea());
                reportPublicField.setCreateUser(userId);
                reportPublicField.setDelFlag("0");
                reportPublicFieldRepository.save(reportPublicField);
            }
        }catch (Exception e) {
            if (e.getMessage().contains("不是合法")) {
                map.put("res",res);
                map.put("mess","上传失败! 上传的文件模板有误,请检查表头是否改动！");
            }
            e.printStackTrace();
        }
        map.put("res",res);
        return map;
    }

    @Override
    public Map<String, Object> getSamPoiByXsemId(String xsemId, int curPage, int pageSize) {
        return samPoiDataRepository.getSamPoiByXsemId(xsemId,curPage,pageSize);
    }

    @Override
    public List<SamPoiData> getAllData(SamPoiDataQuaParams queParams) {
        return samPoiDataRepository.getAllData(queParams);
    }

    @Override
    public List<SamPoiData> findBySamplingPointName(String samplingPointName,String xsemId) {
        return samPoiDataRepository.findBySamplingPointName(samplingPointName,xsemId);
    }

    @Override
    public List<SamPoiData> getUnassociatedData(String xsemId) {
        return samPoiDataRepository.getUnassociatedData(xsemId);
    }
}
